<!-- This microfrontend HTML file is used to test a variety of functionality -->
<!doctype html>
<html lang="en">
  <head>
    <title></title>
    <meta charset="utf-8" />
    <script src="./luigi-client.js"></script>
    <style>
      html,
      body {
        position: relative;
      }

      #imgCnt img {
        width: 100%;
      }

      #imgCnt {
        text-align: center;
      }

      #textCnt {
        padding: 30px;
        text-align: center;
        font-family: '72', sans-serif;
        visibility: hidden;
      }

      #textCnt.visible {
        visibility: visible;
      }
    </style>
  </head>

  <body style="-webkit-font-smoothing: antialiased; color: #515559">
    <div id="imgCnt"></div>
    <div id="textCnt">
      <h1 id="title">iFrame based Container</h1>
      <p id="content">Some content</p>
      <button onclick="testNav()">test navigate</button>
      <button onclick="testCustom()">test custom message</button>
      <button onclick="testAddSearchParams()">Test add search params</button>
      <button onclick="testAddNodeParams()">Test add node params</button>
      <button onclick="testGetNodeParams()">Test get node params</button>
      <button onclick="testShowConfirmationModal()">test show confirmation modal</button>
      <button onclick="testConfirmationModalCallback()">
        test confirmation modal callback
      </button>
      <button onclick="testShowLoadingIndicator()">test show loading indicator</button>
      <button onclick="testHideLoadingIndicator()">test hide loading indicator</button>
      <button onclick="testGetHistoryState()">test history state</button>
      <button onclick="testGetContext()">Get Context</button>
      <button onclick="testUpdateModalPathInternalNavigation()">
        test update modal path internal navigation
      </button>
      <button onclick="testSetCurrentLocale()">test set current locale</button>
      <button onclick="testSetLocalStorage()">test set local storage</button>
      <button onclick="testRuntimeErrorRequest()">
        test runtime error handling request
      </button>
      <button onclick="testSetAnchorLink()">test set anchor link</button>
      <button onclick="testBackNavigation()">test back navigation</button>
      <button onclick="testGetCurrentRoute()">test get current route</button>
      <button onclick="testNavigationFinished()">test navigate.ok</button>
      <button onclick="testUpdateModalPath()">test update modal path</button>
      <button onclick="testCheckPathExists()">test check path exists</button>
      <button onclick="testSetDirtyStatus()">test set dirty status</button>
      <button onclick="testShowAlert()">test show alert</button>
      <button onclick="testGetPathParams()">test get path params</button>
      <button onclick="testGetCoreSearchParams()">test get core search params</button>
      <button onclick="testGetToken()">test get token</button>
      <button onclick="testAlertCallback()">test alert callback</button>
      <button onclick="testShowAlertWithNotifyAlertClosed()">
        test showAlert with notifyAlertClosed
      </button>
      <button onclick="goBack()">test goBack()</button>
      <button onclick="openAsModal()">test openAsModal()</button>
      <button onclick="openAsDrawer()">test openAsDrawer()</button>
      <button onclick="openAsSplitview()">test openAsSplitview()</button>
      <button onclick="updateModalSettings()">test updateModalSettings</button>
      <button onclick="getCurrentTheme()">get current theme</button>
      <button onclick="getCurrentLocale()">get current locale</button>
      <button onclick="getActiveFeatureToggleList()">
        get active feature toggle list
      </button>
      <button onclick="testCloseCurrentModal()">test close current modal</button>
      <br /><br />
      <span id="result"></span>
    </div>

    <script>
      // List of onclick handlers for client calls

      function openAsModal() {
        LuigiClient.linkManager().openAsModal('openAsModal-iframe', {
          title: 'Modal Title',
          size: 'm',
        });
      }

      function updateModalSettings() {
        LuigiClient.linkManager().updateModalSettings({
          title: 'Updated modal title',
          size: 'l',
        });
      }

      function openAsDrawer() {
        LuigiClient.linkManager().openAsDrawer('openAsDrawer-iframe', {
          size: 's',
        });
      }

      function openAsSplitview() {
        LuigiClient.linkManager().openAsDrawer('openAsSplitview-iframe', {
          size: 'l',
        });
      }

      function goBack() {
        LuigiClient.linkManager().goBack();
      }

      function testNav() {
        LuigiClient.linkManager().navigate('/');
      }

      function testCustom() {
        LuigiClient.sendCustomMessage({ id: 'my.customMessage', bar: 'foo' });
      }

      function testAddSearchParams() {
        LuigiClient.addCoreSearchParams({ luigi: 'searchParams' }, false);
      }

      function testAddNodeParams() {
        LuigiClient.addNodeParams({ luigi: 'nodeParams' }, true);
      }

      function testGetNodeParams() {
        const nodeParams = LuigiClient.getNodeParams();
        document.querySelector('#result').innerHTML =
          `nodeParams: ${JSON.stringify(nodeParams)}`;
      }

      function testShowConfirmationModal() {
        const settings = {
          type: 'confirmation',
          header: 'Confirmation',
          body: 'Are you sure you want to do this?',
          buttonConfirm: 'Yes',
          buttonDismiss: 'No',
        };

        LuigiClient.uxManager()
          .showConfirmationModal(settings)
          .then(() => console.log('Modal confirmed'))
          .catch(() => console.log('Modal dissmissed'));
      }

      function testConfirmationModalCallback() {
        LuigiClient.uxManager()
          .showConfirmationModal({
            type: 'confirmation',
            header: 'Callback Test',
            body: 'Are you sure you want to do this?',
            buttonConfirm: 'Yes',
            buttonDismiss: 'No',
          })
          .then(() => {
            document.querySelector('#result').innerHTML = 'showConfirmationModal: true';
          });
      }

      function testShowLoadingIndicator() {
        LuigiClient.uxManager().showLoadingIndicator();
      }

      function testHideLoadingIndicator() {
        LuigiClient.uxManager().hideLoadingIndicator();
      }

      function testGetHistoryState() {
        LuigiClient.sendCustomMessage({
          id: 'my.historyMessage',
          ...{ state: window.history.state },
        });
      }

      function testGetContext() {
        LuigiClient.sendCustomMessage({
          id: 'my.contextMessage',
          ...LuigiClient.getContext(),
        });
      }

      function testUpdateModalPathInternalNavigation() {
        const history = true;
        const link = '/test/route';
        const modal = { title: 'Some modal' };

        this.LuigiClient.linkManager().updateModalPathInternalNavigation(
          link,
          modal,
          history,
        );
      }

      function testSetCurrentLocale() {
        LuigiClient.uxManager().setCurrentLocale('en');
      }

      function testSetLocalStorage() {
        LuigiClient.storageManager().setItem('keyExample', 'valueExample').then();
      }

      // this is ran only when client is initialized and an error has occurred
      function testRuntimeErrorRequest() {
        // since this scenario is not caused by a luigi client call,
        // here we intentionally cause an error that is then to be catched by the client internally. The latter then sends a message to core with runtime error message
        const badCode = 'const s;';
        eval(badCode);
      }

      function testSetAnchorLink() {
        LuigiClient.setAnchor('luigi');
      }

      function testBackNavigation() {
        LuigiClient.linkManager().goBack();
      }

      function testGetCurrentRoute() {
        LuigiClient.linkManager()
          .getCurrentRoute()
          .then((result) => {
            document.querySelector('#result').innerHTML = `getCurrentRoute: ${result}`;
          });
      }

      function testNavigationFinished() {
        // TODO: discuss if actually needed as the only scenario is when microfrontend initially starts
      }

      function testUpdateModalPath() {
        LuigiClient.linkManager().updateModalPathInternalNavigation('microfrontend');
      }

      function testCheckPathExists() {
        LuigiClient.linkManager()
          .pathExists('/projects/pr2')
          .then((result) => {
            document.querySelector('#result').innerHTML = `pathExists: ${result}`;
          });
      }

      function testSetDirtyStatus() {
        LuigiClient.uxManager().setDirtyStatus(true);
      }

      function testGetPathParams() {
        const pathParams = LuigiClient.getPathParams();
        document.querySelector('#result').innerHTML =
          `pathParams: ${JSON.stringify(pathParams)}`;
      }

      function testGetCoreSearchParams() {
        const searchParams = LuigiClient.getCoreSearchParams();
        console.log('searchParmas', searchParams);
        document.querySelector('#result').innerHTML =
          `searchParams: ${JSON.stringify(searchParams)}`;
      }

      function testGetToken() {
        // send back message with get Token value
        LuigiClient.sendCustomMessage({
          id: 'token.updated',
          value: LuigiClient.getToken(),
        });
      }

      function testShowAlert() {
        let dt = new Date();
        let time = dt.getMilliseconds() + '';
        time = time.substr(time.length - 3);
        const settings = {
          text:
            'This is an alert message {goToHome} with a {relativePath}. You can go to {goToOtherProject}. {neverShowItAgain}' +
            time,
          type: 'info',
          links: {
            goToHome: { text: 'homepage', url: '/overview' },
            goToOtherProject: { text: 'other project', url: '/projects/pr2' },
            relativePath: { text: 'relative hide side nav', url: 'hideSideNav' },
            neverShowItAgain: {
              text: "Don't show this again",
              dismissKey: 'neverShowItAgain',
            },
          },
          closeAfter: 300000,
        };
        LuigiClient.uxManager()
          .showAlert(settings)
          .then((param) => {
            console.log('Callback called on microfrontend', param);
          });
      }

      function testAlertCallback() {
        LuigiClient.uxManager()
          .showAlert({
            text: 'Callback Test',
            type: 'info',
          })
          .then((result) => {
            document.querySelector('#result').innerHTML = `showAlert: ${result}`;
          });
      }

      function getCurrentTheme() {
        const currentTheme = LuigiClient.uxManager().getCurrentTheme();
        document.querySelector('#result').innerHTML =
          `currentTheme: ${JSON.stringify(currentTheme)}`;
      }

      function getCurrentLocale() {
        const currentLocale = LuigiClient.uxManager().getCurrentLocale();
        document.querySelector('#result').innerHTML =
          `currentLocale: ${JSON.stringify(currentLocale)}`;
      }

      function getActiveFeatureToggleList() {
        const featureToggleList = LuigiClient.getActiveFeatureToggles();
        document.querySelector('#result').innerHTML =
          `activeFeatureToggleList: ${JSON.stringify(featureToggleList)}`;
      }

      function testShowAlertWithNotifyAlertClosed() {
        let dt = new Date();
        let time = dt.getMilliseconds() + '';
        time = time.substr(time.length - 3);
        const settings = {
          text:
            'This is an alert message {goToHome} with a {relativePath}. You can go to {goToOtherProject}. {neverShowItAgain}' +
            time,
          type: 'info',
          links: {
            goToHome: { text: 'homepage', url: '/overview' },
            goToOtherProject: { text: 'other project', url: '/projects/pr2' },
            relativePath: { text: 'relative hide side nav', url: 'hideSideNav' },
            neverShowItAgain: {
              text: "Don't show this again",
              dismissKey: 'neverShowItAgain',
            },
          },
          notifyAlertClosed: true,
          closeAfter: 300000,
        };
        LuigiClient.uxManager()
          .showAlert(settings)
          .then((param) => {
            const span = document.createElement('span');
            // span.setAttribute('id', 'callbackCloseAlert');
            span.innerHTML = 'Callback called on iframe ' + param;
            document.body.appendChild(span);
            console.log('Callback called on microfrontend', param);
          });
      }

      function testCloseCurrentModal() {
        LuigiClient.uxManager().closeCurrentModal();
      }

      function updateFn(context) {
        // report-navigation-completed-request will be detected since
        // context update is tied to navigation being completed
        if (context.title) {
          document.getElementById('title').innerHTML = context.title;
        }
        if (context.content) {
          document.getElementById('content').innerHTML = context.content;
        }
        if (context.imgUrl) {
          var iwidth = !isNaN(context.imgWidth)
            ? 'width: ' + context.imgWidth + 'px'
            : '';
          document.getElementById('imgCnt').innerHTML =
            "<img src='" +
            context.imgUrl +
            "' style='" +
            iwidth +
            '; margin-top: ' +
            (context.imgTopMargin ? '5' : '') +
            "0px'>";
        }
        document.getElementById('textCnt').classList.add('visible');
      }
      LuigiClient.addInitListener(updateFn);
      LuigiClient.addContextUpdateListener(updateFn);
      LuigiClient.addCustomMessageListener('update', (msg) => {
        console.log('Custom Message Received inside iframe Container', msg);
        document.getElementById('content').innerHTML =
          'Received Custom Message: ' + msg.dataToSend;
      });

      // fallback visibility if no initlistener called for 3 seconds
      setTimeout(function () {
        document.getElementById('textCnt').classList.add('visible');
      }, 3000);
    </script>
  </body>
</html>
